package casa.depesos.app.com.activity;

import static casa.depesos.app.com.activity.TouchActivity.isEmpty;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;

import casa.depesos.app.com.R;
import casa.depesos.app.com.databinding.ActivityCardSureBinding;
import casa.depesos.app.com.frag.EmptyFragment;
import casa.depesos.app.com.frag.NetFailFragment;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.CardInfoBean;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.data.CardInfo;
import casa.depesos.app.com.http.req.CardInfoReq;
import casa.depesos.app.com.http.req.CheckIdReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class CardSureActivity extends BaseActivity {

    ActivityCardSureBinding binding;

    @Override
    protected boolean needPadding() {
        return false;
    }

    final String title = "Verificación de identidad";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCardSureBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.top.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
        binding.top.back.setOnClickListener(v -> {
            if (getIntent().getBooleanExtra("direct", false)) {
                Report.click("ACTION_LL_002");
            }
            if (needKeep()) {
                dealBack();
            } else {
                finish();
            }
        });
        binding.top.title.setText(title);

        Utils.setEditTextInputNoSpaceStart(binding.name, 50);
        Utils.setEditTextInputNoSpaceStart(binding.fName, 50);
        Utils.setEditTextInputNoSpaceStart(binding.mName, 50);
        Utils.setEditTextInputSpace(binding.id, 18);

        if (getIntent().getIntExtra("from", 0) == 1) {
            binding.bottom.setVisibility(View.GONE);
            binding.tip.setVisibility(View.GONE);
            disableAll(binding.getRoot());
            binding.top.back.setEnabled(true);
        }

        if (getIntent().hasExtra("card")) {
            CardInfo info = getIntent().getParcelableExtra("card");
            init(info);
        } else {
            getData();
        }
        if (getIntent().getBooleanExtra("direct", false)) {
            Report.show("ACTION_LL_001");
        }
    }

    public void getData() {
        showLoading();
        clearFragment(getSupportFragmentManager());
        new CardInfoReq(fromMe()).req(new ReqCallback<CardInfoBean>() {
            @Override
            public void callback(boolean success, CardInfoBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    init(bean.card);
                } else if (bean != null && fromMe()) {
                    replaceFragment(R.id.frame, new EmptyFragment().setTitle(title));
                } else {
                    replaceFragment(R.id.frame, new NetFailFragment().setTitle(title));
                }
            }
        });
    }

    private boolean fromMe() {
        return getIntent().getIntExtra("from", 0) == 1;
    }

    private void init(CardInfo info) {

        Glide.with(this).load(info.front).placeholder(R.mipmap.default_pic).error(R.mipmap.default_pic).into(binding.front);
        Glide.with(this).load(info.back).placeholder(R.mipmap.default_pic).error(R.mipmap.default_pic).into(binding.cardBack);

        addWatcher(binding.name, "ACTION_LL_012", false);
        addWatcher(binding.fName, "ACTION_LL_010", false);
        addWatcher(binding.mName, "ACTION_LL_011", false);
        addWatcher(binding.id, "ACTION_LL_013", true);

        binding.name.setText(info.name);
        binding.fName.setText(info.fName);
        binding.mName.setText(info.mName);
        binding.id.setText(info.id);

        binding.next.setOnClickListener(v -> {
            next();
        });
    }

    private void addWatcher(EditText et, String event, boolean big) {
        et.addTextChangedListener(new TextWatcher() {
            boolean report = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (big) {
                    String input = s.toString();
                    String uppercaseInput = input.toUpperCase();
                    if (uppercaseInput.equals(input)) {
                        return;
                    }
                    et.setText(uppercaseInput);
                    et.setSelection(uppercaseInput.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!report && s.toString().trim().length() > 0) {
                    report = true;
                    Report.click(event);
                }
                check();
            }
        });
    }

    private boolean check() {
        binding.err.setVisibility(View.GONE);
        String name = binding.name.getText().toString().trim();
        String fName = binding.fName.getText().toString().trim();
        String mName = binding.mName.getText().toString().trim();
        String id = binding.id.getText().toString().trim();
        boolean valid = true;
        if (isEmpty(name, fName, mName)) {
            valid = false;
            binding.next.setEnabled(false);
        } else {
            binding.next.setEnabled(true);
        }
        if (id.length() != 18) {
            valid = false;
        }
        if (valid) {
            binding.next.setAlpha(1f);
        } else {
            binding.next.setAlpha(0.6f);
        }
        return valid;
    }

    private void next() {
        Report.click("ACTION_LL_014");
        if (!check()) {
            String id = binding.id.getText().toString().trim();
            if (id.length() != 8) {
                binding.err.setVisibility(View.VISIBLE);
            }
            return;
        }
        String name = binding.name.getText().toString().trim();
        String fName = binding.fName.getText().toString().trim();
        String mName = binding.mName.getText().toString().trim();
        String id = binding.id.getText().toString().trim();
        CardInfo tmp = new CardInfo();
        tmp.name = name;
        tmp.fName = fName;
        tmp.mName = mName;
        tmp.id = id;
        showLoading();
        new CheckIdReq(tmp).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (Constant.white || success && bean.isValid()) {
                    toFace();
                }
            }
        });
    }

    private void toFace() {
        if (Constant.white) {
            Utils.setStatus(40);
        }
        Intent i = new Intent(this, FaceActivity.class);
        startActivity(i);
        finish();
    }

    protected void disableAll(View group) {
        if (group instanceof ViewGroup) {
            int j = ((ViewGroup) group).getChildCount();
            for (int i = 0; i < j; i++) {
                View view = ((ViewGroup) group).getChildAt(i);
                if (view instanceof ViewGroup) {
                    disableAll(view);
                } else {
                    view.setEnabled(false);
                }
            }
        } else {
            group.setEnabled(false);
        }
    }

    @Override
    protected boolean needKeep() {
        return !fromMe();
    }
}
